<template>
  <div class="analyze-service-components">
    <el-row :gutter="20">
      <!-- 左侧功能区 -->
      <el-col :span="6">
        <el-card>
          <h3>模型生命周期管理</h3>
          <el-button type="primary" @click="deployModel">版本发布</el-button>
          <div v-if="modelDeployed" class="deploy-info">
            <p>版本号：{{ modelInfo.version }}</p>
            <p>服务端口：{{ modelInfo.port }}</p>
            <p>负载均衡实例数：{{ modelInfo.instances }}</p>
          </div>
        </el-card>
        <el-card style="margin-top: 20px;">
          <h3>效果评估</h3>
          <el-button type="success" @click="startEvaluation" :disabled="evaluating">开始评估</el-button>
          <div v-if="evaluating" style="margin: 10px 0;">
            <el-tag type="info">评估中...</el-tag>
          </div>
          <div v-if="evalResult">
            <p>推理延迟：<span :style="{color: evalResult.latency > 50 ? 'red' : 'green'}">{{ evalResult.latency }}ms</span></p>
            <p>准确率波动：<span :style="{color: Math.abs(evalResult.accuracyFluctuation) > 2 ? 'red' : 'green'}">{{ evalResult.accuracyFluctuation }}%</span></p>
            <p>测试用例：{{ evalResult.testCase }}</p>
          </div>
        </el-card>
        <el-card style="margin-top: 20px;">
          <h3>内置算法库</h3>
          <el-list>
            <el-list-item
              v-for="algo in algorithmTemplates"
              :key="algo.id"
              @dblclick="editAlgorithm(algo)"
              style="cursor: pointer;"
            >
              <span>{{ algo.name }}</span>
              <el-tag size="mini" style="margin-left: 8px;">模板</el-tag>
            </el-list-item>
          </el-list>
        </el-card>
      </el-col>

      <!-- 中间编排画布 -->
      <el-col :span="12">
        <el-card>
          <h3>可视化编排</h3>
          <div class="orchestration">
            <div class="module-list">
              <div
                class="draggable-module"
                v-for="mod in availableModules"
                :key="mod.type"
                draggable="true"
                @dragstart="onDragStart(mod)"
              >
                {{ mod.name }}
              </div>
            </div>
            <div
              class="canvas"
              @dragover.prevent
              @drop="onDrop"
            >
              <div
                v-for="(node, idx) in canvasModules"
                :key="node.id"
                class="canvas-node"
                :style="{top: node.y+'px', left: node.x+'px'}"
                @mousedown="onNodeMouseDown($event, node)"
              >
                <div class="node-title">{{ node.name }}</div>
                <div class="node-params">
                  <el-input
                    v-model="node.input.deviceId"
                    size="mini"
                    placeholder="设备ID"
                    style="margin-bottom: 4px;"
                  />
                  <el-date-picker
                    v-model="node.input.timeRange"
                    type="daterange"
                    size="mini"
                    start-placeholder="开始时间"
                    end-placeholder="结束时间"
                    style="width: 100%;"
                  />
                  <el-input
                    v-model="node.outputFormat"
                    size="mini"
                    placeholder="输出格式"
                    style="margin-top: 4px;"
                  />
                </div>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click.stop="removeNode(node.id)"
                  circle
                  style="position: absolute; top: 2px; right: 2px;"
                />
              </div>
              <!-- 连线简单模拟 -->
              <svg class="canvas-lines" v-if="canvasLinks.length">
                <line
                  v-for="(link, idx) in canvasLinks"
                  :key="idx"
                  :x1="getNodeCenter(link.from).x"
                  :y1="getNodeCenter(link.from).y"
                  :x2="getNodeCenter(link.to).x"
                  :y2="getNodeCenter(link.to).y"
                  stroke="#409EFF"
                  stroke-width="2"
                  marker-end="url(#arrow)"
                />
                <defs>
                  <marker id="arrow" markerWidth="10" markerHeight="10" refX="10" refY="5" orient="auto">
                    <path d="M0,0 L10,5 L0,10 Z" fill="#409EFF"/>
                  </marker>
                </defs>
              </svg>
            </div>
            <div class="canvas-actions">
              <el-button type="primary" size="mini" @click="startLinking" :disabled="linking">连线</el-button>
              <el-button type="success" size="mini" @click="saveCanvas">保存流程</el-button>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- 右侧算法参数编辑/服务生成 -->
      <el-col :span="6">
        <el-card>
          <h3>算法服务生成</h3>
          <div v-if="editingAlgorithm">
            <el-form :model="editingAlgorithm" label-width="100px">
              <el-form-item label="算法名称">
                <el-input v-model="editingAlgorithm.name" disabled />
              </el-form-item>
              <el-form-item label="振动烈度阈值">
                <el-input-number
                  v-model="editingAlgorithm.threshold"
                  :min="0"
                  :step="0.1"
                  :precision="1"
                />
              </el-form-item>
            </el-form>
            <el-button type="primary" @click="saveAlgorithm">保存为新服务</el-button>
          </div>
          <div v-else>
            <p>双击左侧算法库模板可编辑参数并生成新服务接口。</p>
            <ul>
              <li v-for="srv in algorithmServices" :key="srv.id">
                <el-tag type="success">{{ srv.name }}</el-tag>
                <span>阈值: {{ srv.threshold }}</span>
              </li>
            </ul>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid';

export default {
  name: 'AnalyzeServiceComponents',
  data() {
    return {
      // 模型部署信息
      modelDeployed: false,
      modelInfo: {
        version: '1.0',
        port: 8080,
        instances: 2
      },
      // 效果评估
      evaluating: false,
      evalResult: null,
      // 算法库与服务
      algorithmTemplates: [
        { id: 'algo1', name: '齿轮箱故障检测', threshold: 7.1 }
      ],
      editingAlgorithm: null,
      algorithmServices: [],
      // 拖拽编排
      availableModules: [
        { type: 'fault-diagnosis', name: '故障诊断模块' },
        { type: 'energy-analysis', name: '能耗分析模块' }
      ],
      canvasModules: [],
      canvasLinks: [],
      linking: false,
      linkFrom: null,
      // 拖拽辅助
      dragModule: null,
      dragOffset: { x: 0, y: 0 }
    };
  },
  mounted() {
    // 加载本地数据
    const savedServices = localStorage.getItem('algorithmServices');
    if (savedServices) {
      this.algorithmServices = JSON.parse(savedServices);
    }
    const savedCanvas = localStorage.getItem('canvasModules');
    if (savedCanvas) {
      this.canvasModules = JSON.parse(savedCanvas);
    }
    const savedLinks = localStorage.getItem('canvasLinks');
    if (savedLinks) {
      this.canvasLinks = JSON.parse(savedLinks);
    }
  },
  methods: {
    // 模型部署
    deployModel() {
      this.modelDeployed = true;
      this.$message.success('模型已部署到生产环境！');
    },
    // 效果评估
    startEvaluation() {
      this.evaluating = true;
      this.evalResult = null;
      setTimeout(() => {
        // mock评估结果
        const latency = Math.round(30 + Math.random() * 40); // 30~70ms
        const accuracyFluctuation = (Math.random() * 4 - 2).toFixed(2); // -2%~+2%
        this.evalResult = {
          latency,
          accuracyFluctuation,
          testCase: '异常振动数据'
        };
        this.evaluating = false;
      }, 1500);
    },
    // 算法库编辑
    editAlgorithm(algo) {
      this.editingAlgorithm = { ...algo };
    },
    saveAlgorithm() {
      const newAlgo = {
        ...this.editingAlgorithm,
        id: uuidv4()
      };
      this.algorithmServices.push(newAlgo);
      localStorage.setItem('algorithmServices', JSON.stringify(this.algorithmServices));
      this.$message.success('新算法服务已生成！');
      this.editingAlgorithm = null;
    },
    // 拖拽编排
    onDragStart(mod) {
      this.dragModule = mod;
    },
    onDrop(e) {
      if (!this.dragModule) return;
      const rect = e.target.getBoundingClientRect();
      const x = e.clientX - rect.left - 60;
      const y = e.clientY - rect.top - 20;
      this.canvasModules.push({
        id: uuidv4(),
        type: this.dragModule.type,
        name: this.dragModule.name,
        x, y,
        input: { deviceId: '', timeRange: [] },
        outputFormat: ''
      });
      this.dragModule = null;
      this.saveCanvas();
    },
    onNodeMouseDown(e, node) {
      if (this.linking) {
        if (!this.linkFrom) {
          this.linkFrom = node.id;
          this.$message.info('请选择目标节点完成连线');
        } else if (this.linkFrom !== node.id) {
          this.canvasLinks.push({ from: this.linkFrom, to: node.id });
          this.linkFrom = null;
          this.linking = false;
          this.saveCanvas();
        }
        e.stopPropagation();
        return;
      }
      // 拖动节点
      const startX = e.clientX, startY = e.clientY;
      const origX = node.x, origY = node.y;
      const onMouseMove = (moveEvent) => {
        node.x = origX + moveEvent.clientX - startX;
        node.y = origY + moveEvent.clientY - startY;
      };
      const onMouseUp = () => {
        document.removeEventListener('mousemove', onMouseMove);
        document.removeEventListener('mouseup', onMouseUp);
        this.saveCanvas();
      };
      document.addEventListener('mousemove', onMouseMove);
      document.addEventListener('mouseup', onMouseUp);
    },
    startLinking() {
      this.linking = true;
      this.linkFrom = null;
      this.$message.info('请点击起始节点，再点击目标节点');
    },
    removeNode(id) {
      this.canvasModules = this.canvasModules.filter(n => n.id !== id);
      this.canvasLinks = this.canvasLinks.filter(l => l.from !== id && l.to !== id);
      this.saveCanvas();
    },
    saveCanvas() {
      localStorage.setItem('canvasModules', JSON.stringify(this.canvasModules));
      localStorage.setItem('canvasLinks', JSON.stringify(this.canvasLinks));
      this.$message.success('流程已保存');
    },
    getNodeCenter(nodeId) {
      const node = this.canvasModules.find(n => n.id === nodeId);
      if (!node) return { x: 0, y: 0 };
      return { x: node.x + 60, y: node.y + 30 };
    }
  }
};
</script>

<style scoped>
.analyze-service-components {
  padding: 20px;
}
.deploy-info {
  margin-top: 10px;
  background: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
}
.orchestration {
  display: flex;
  flex-direction: row;
}
.module-list {
  width: 120px;
  margin-right: 20px;
}
.draggable-module {
  background: #ecf5ff;
  border: 1px solid #b3d8ff;
  border-radius: 4px;
  padding: 8px;
  margin-bottom: 10px;
  text-align: center;
  cursor: grab;
  user-select: none;
}
.canvas {
  position: relative;
  flex: 1;
  min-height: 400px;
  background: #fafafa;
  border: 1px dashed #d3dce6;
  border-radius: 6px;
  overflow: hidden;
}
.canvas-node {
  position: absolute;
  width: 120px;
  min-height: 80px;
  background: #fff;
  border: 1px solid #d3dce6;
  border-radius: 6px;
  box-shadow: 0 2px 8px #f0f1f2;
  padding: 8px;
  cursor: move;
  z-index: 2;
}
.node-title {
  font-weight: bold;
  margin-bottom: 6px;
}
.node-params {
  font-size: 12px;
}
.canvas-lines {
  position: absolute;
  top: 0; left: 0; width: 100%; height: 100%;
  pointer-events: none;
  z-index: 1;
}
.canvas-actions {
  margin-top: 10px;
  text-align: right;
}
</style>

<!--
依赖说明：
- 需已安装 element-ui
- 需已安装 uuid（npm install uuid）
-->
